from loguru import logger
from nicegui import ui
from rr.api import ServerHelper

server_helper = ServerHelper()


def ui_file(file_id):
    logger.info(f"ui_file {file_id}")
    _ui_file(file_id)


@ui.refreshable
def _ui_file(file_id, element=None):
    # Get file info
    file_info = server_helper.get_file_info(file_id)

    with ui.card().classes("w-full"):
        ui.label(f"File: {file_id}").classes("text-xl font-bold")

        # Show file metadata
        with ui.expansion("File Information", icon="info").classes("w-full"):
            with ui.grid(columns=2).classes("w-full"):
                ui.label("File ID:").classes("font-bold")
                ui.label(file_id)
                ui.label("Type:").classes("font-bold")
                ui.label(file_info.type_)
                ui.label("Content Type:").classes("font-bold")
                ui.label(file_info.content_type)
                if file_info.task_hash:
                    ui.label("Task:").classes("font-bold")
                    ui.link(file_info.task_hash, f"/task_detail/{file_info.task_hash}")
        # # Show file content based on content type
        with ui.expansion("File Content", icon="description").classes("w-full"):
            if file_info.content_type.startswith("text/"):
                # For text files, read and display content
                with ui.element(tag="pre").classes("w-full overflow-auto"):
                    file_content = server_helper.get_file(file_id).read().decode()
                    ui.html(file_content)
            elif file_info.content_type.startswith("image/"):
                # For images, display them
                ui.image(
                    f"data:{file_info.content_type};base64,"
                    + server_helper.get_file(file_id).read().decode()
                )
            else:
                # For other types, show download option
                ui.label("This file type cannot be displayed in the browser.")
                with ui.row():
                    ui.button(
                        "Download File",
                        icon="download",
                        on_click=lambda: server_helper.download_file(
                            file_id, f"{file_id}"
                        ),
                    )
                    ui.button(
                        "Copy Download Link",
                        icon="content_copy",
                        on_click=lambda: ui.clipboard.write(
                            server_helper.get_file_download_url(file_id)
                        ),
                    )


page_config = {
    "nav_entry": [
        {
            "title": None,
            "url": "/file/{file_id}",
            "function": ui_file,
        }
    ]
}
